#!/usr/bin/env groovy

def git_auth = "1fa96864-5699-483b-a920-2af11df61119"
def harbor_auth = "1e0ae5b9-b151-45b9-a94f-bd02d803ff22"
def kubectl_auth = "c26898c2-92c3-4c19-8490-9cf8ff7918ef"

pipeline {
    agent {
        kubernetes {
            yaml '''
apiVersion: v1
kind: Pod
metadata:
  name: jenkins-slave
  namespace: jenkins
spec:
  tolerations:
  - key: "no-pod"
    operator: "Exists"
    effect: "NoSchedule"
  containers:
  - name: docker
    #image: docker:27.1.1
    image: ccr.ccs.tencentyun.com/huanghuanhui/docker:27.1.1
    imagePullPolicy: IfNotPresent
    readinessProbe:
      exec:
        command: [sh, -c, "ls -S /var/run/docker.sock"]
    command:
    - sleep
    args:
    - 99d
    volumeMounts:
    - name: docker-socket
      mountPath: /var/run
  - name: docker-daemon
    #image: docker:27.1.1-dind
    image: ccr.ccs.tencentyun.com/huanghuanhui/docker:27.1.1-dind
    imagePullPolicy: IfNotPresent
    securityContext:
      privileged: true
    volumeMounts:
    - name: docker-socket
      mountPath: /var/run
  - name: maven
    #image: maven:3.8.1-jdk-8
    image: ccr.ccs.tencentyun.com/huanghuanhui/maven:3.8.1-jdk-8
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
    volumeMounts:
    - name: maven-cache
      mountPath: /root/.m2/repository
  - name: kubectl
    image: ccr.ccs.tencentyun.com/huanghuanhui/kubectl:v1.6.0
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
  - name: jnlp
    #image: jenkins/inbound-agent:3206.vb_15dcf73f6a_9-2
    image: ccr.ccs.tencentyun.com/huanghuanhui/jenkins-inbound-agent:3206.vb_15dcf73f6a_9-2
    imagePullPolicy: IfNotPresent
  volumes:
  - name: docker-socket
    emptyDir: {}
  - name: maven-cache
    persistentVolumeClaim:
      claimName: jenkins-slave-maven-cache
'''
        }
    }

environment {
AppName = "${AppName}"
GitRepo = "${GitRepo}"
GitBranch = "${GitBranch}"
Server = "${Server}"
RepoName = "${RepoName}"
BaseImage = "${BaseImage}"
}

    parameters {
        string(name: 'AppName', defaultValue: '', description: '服务名')
        string(name: 'GitRepo', defaultValue: '', description: '代码仓库地址')
        string(name: 'GitBranch', defaultValue: '', description: '代码版本')
        string(name: 'Server', defaultValue: '', description: '仓库地址')
        string(name: 'RepoName', defaultValue: '', description: '仓库名字（仓库自动创建）')
        string(name: 'BaseImage', defaultValue: '', description: '基础镜像')
    }
    
    stages {
        stage('拉取代码') {
            steps {
            git branch: "${GitBranch}", credentialsId: "${git_auth}", url: "${GitRepo}"
            }
        }

        stage('代码编译') {
            steps {
              container('maven') {
                sh """
                  mvn -U clean install -Dmaven.test.skip=true
                """
                }
            }
        }

        stage('打包镜像') {
            steps {
              script {env.GIT_COMMIT_MSG = sh (script: 'git rev-parse --short HEAD', returnStdout: true).trim()}
              container('docker') {
sh '''
cat > Dockerfile << EOF
FROM ${BaseImage}
WORKDIR /usr/local/src/
ADD ./${AppName}/target/${AppName}.jar /usr/local/src/${AppName}.jar
EOF

docker build -t ${Server}/${RepoName}:${GitBranch}-${GIT_COMMIT_MSG}-${BUILD_ID} .
'''
                }
            }
        }

        stage('推送镜像') {
            steps {
              container('docker') {
                withCredentials([usernamePassword(credentialsId: "${harbor_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
                sh """
                docker login -u ${username} -p '${password}' ${Server}
                docker push ${Server}/${RepoName}:${GitBranch}-${GIT_COMMIT_MSG}-${BUILD_ID}
                """
                   }
                }
            }
        }

        stage('滚动更新') {
            steps {
              container('kubectl') {
              configFileProvider([configFile(fileId: "${kubectl_auth}", variable: 'kubeconfig')]) {
                sh """
                mkdir -p ~/.kube && cp ${kubeconfig} ~/.kube/config
                 /app/kubectl-argo-rollouts-linux-amd64 set image ${AppName} "*=${Server}/${RepoName}:${GitBranch}-${GIT_COMMIT_MSG}-${BUILD_ID}" -n prod
                """
                   }
                }
            }
        }
    }
}

post {
        success {
            script {
                def message = """
                    {
                        "msgtype": "markdown",
                        "markdown": {
                            "content": "「stupid」发布系统通知
                            > 当前状态: <font color=\\\"warning\\\">构建成功</font>
                            > 提交信息: <font color=\\\"warning\\\">${COMMIT_INFO}</font>
                            > 提交人员: ${COMMIT_USER}
                            > 发布应用: <font color=\\\"warning\\\">${APPLICATION_NAME}</font>
                            > 提交时间: <font color=\\\"comment\\\">${COMMIT_TIME}</font>
                            > 当前版本: <font color=\\\"comment\\\">dev</font>
                        }
                    }
                """
                sh """
                    curl -s -d '${message}' -H 'Content-Type: application/json' -i -XPOST ${QYWX_URL}
                """
            }
        }
        failure {
            script {
                def message = """
                    {
                        "msgtype": "markdown",
                        "markdown": {
                            "content": "「stupid」发布系统通知
                            > 当前状态: <font color=\\\"warning\\\">构建失败</font>
                            > 提交信息: <font color=\\\"warning\\\">${COMMIT_INFO}</font>
                            > 提交人员: ${COMMIT_USER}
                            > 发布应用: <font color=\\\"warning\\\">${APPLICATION_NAME}</font>
                            > 提交时间: <font color=\\\"comment\\\">${COMMIT_TIME}</font>
                            > 当前版本: <font color=\\\"comment\\\">${params.GIT_BRANCH}</font>
                        }
                    }
                """
                sh """
                    curl -s -d '${message}' -H 'Content-Type: application/json' -i -XPOST https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=227da3b0-60e7-4b30-97fe-ed79a3268f31
                """
            }
        }
    }
}
